// {{ AURA-X: 完全重写 - 基于参考图实现新的UI逻辑. Approval: 寸止 }}

// Tab切换
document.querySelectorAll('.tab-btn').forEach(btn => {
  btn.addEventListener('click', () => {
    const tabName = btn.dataset.tab;
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    btn.classList.add('active');
    document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
    document.getElementById(`${tabName}-tab`).classList.add('active');
  });
});

// ============ 卡信息功能 ============

// 解析卡信息
function parseCards(text) {
  const lines = text.trim().split('\n').filter(line => line.trim());
  const cards = [];
  
  lines.forEach(line => {
    const parts = line.split('|').map(s => s.trim());
    if (parts.length >= 4) {
      cards.push({
        number: parts[0],
        month: parts[1],
        year: parts[2],
        cvc: parts[3],
        id: Date.now() + Math.random()
      });
    }
  });
  
  return cards;
}

// 显示卡信息
function displayCard(card) {
  const masked = card.number.substring(0, 4) + ' **** **** ' + card.number.substring(card.number.length - 4);
  const expiry = `${card.month}/${card.year}`;
  
  return `
    <div class="item-card" data-id="${card.id}">
      <div class="item-content">
        <span class="card-icon">💳</span>
        <span class="card-number">${masked} | ${expiry}</span>
      </div>
      <div class="item-actions">
        <button class="btn btn-edit" data-card-id="${card.id}" data-action="edit-card">编辑</button>
        <button class="btn btn-delete" data-card-id="${card.id}" data-action="delete-card">删除</button>
      </div>
    </div>
  `;
}

// 保存卡信息
document.getElementById('saveCards').addEventListener('click', async () => {
  const text = document.getElementById('cardInput').value;
  const cards = parseCards(text);
  
  if (cards.length === 0) {
    alert('请输入有效的卡信息');
    return;
  }
  
  // 获取现有卡片并追加
  const existing = await chrome.storage.local.get(['cards']);
  const allCards = [...(existing.cards || []), ...cards];
  
  await chrome.storage.local.set({ cards: allCards });
  document.getElementById('cardInput').value = '';
  loadCards();
  showToast('卡信息保存成功');
});

// 加载卡信息列表
async function loadCards() {
  const { cards = [] } = await chrome.storage.local.get(['cards']);
  const listEl = document.getElementById('cardList');
  
  if (cards.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无保存的卡信息</p>';
  } else {
    listEl.innerHTML = cards.map(displayCard).join('');
    
    // 添加事件委托
    listEl.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', function() {
        const cardId = this.getAttribute('data-card-id');
        const action = this.getAttribute('data-action');
        
        if (action === 'delete-card') {
          window.deleteCard(cardId);
        } else if (action === 'edit-card') {
          window.editCard(cardId);
        }
      });
    });
  }
}

// 删除卡
window.deleteCard = async function(id) {
  const { cards = [] } = await chrome.storage.local.get(['cards']);
  const filtered = cards.filter(c => c.id != id);
  await chrome.storage.local.set({ cards: filtered });
  loadCards();
  showToast('卡信息已删除');
};

// 编辑卡（简化版，直接删除重新添加）
window.editCard = function(id) {
  alert('编辑功能：请删除后重新添加');
};

// ============ 用户信息功能 ============

// {{ AURA-X: Modify - 更新用户信息解析逻辑以支持新格式. Approval: 寸止 }}
// 解析用户信息
function parseUsers(text) {
  const users = [];
  const lines = text.trim().split('\n');
  let currentUser = null;
  
  lines.forEach(line => {
    line = line.trim();
    if (!line) return;
    
    // 以"全名："作为新用户的开始标识
    if (line.startsWith('全名：') || line.startsWith('全名:')) {
      if (currentUser) {
        users.push(currentUser);
      }
      const name = line.split('：')[1] || line.split(':')[1];
      currentUser = {
        name: name.trim(),
        id: Date.now() + Math.random()
      };
    } else if (currentUser) {
      // 解析其他字段
      const [key, value] = line.includes('：') ? line.split('：') : line.split(':');
      if (key && value) {
        currentUser[key.trim()] = value.trim();
      }
    }
  });
  
  if (currentUser) {
    users.push(currentUser);
  }
  
  return users;
}

// 显示用户信息
function displayUser(user) {
  const userName = user['全名'] || user.name || '未知用户';
  const postalCode = user['郵遞區號'] || user.postalCode || '';
  const county = user['縣'] || user.county || '';
  const district = user['地區'] || user.district || '';
  const address1 = user['地址第 1 行'] || user.addressLine1 || '';
  const address2 = user['地址第 2 行'] || user.addressLine2 || '';
  
  const fullAddress = [postalCode, county, district, address1, address2]
    .filter(v => v)
    .join(' ');
  
  return `
    <div class="item-card" data-id="${user.id}">
      <div class="item-content">
        <div class="user-header">
          <span class="user-icon">👤</span>
          <span class="user-name">${userName}</span>
        </div>
        <div class="user-details" style="font-size: 12px; color: #666; margin-top: 4px;">
          ${fullAddress || '无地址信息'}
        </div>
      </div>
      <div class="item-actions">
        <button class="btn btn-edit" data-user-id="${user.id}" data-action="edit-user">编辑</button>
        <button class="btn btn-delete" data-user-id="${user.id}" data-action="delete-user">删除</button>
      </div>
    </div>
  `;
}

// 保存用户信息
document.getElementById('saveUsers').addEventListener('click', async () => {
  const text = document.getElementById('userInput').value;
  const users = parseUsers(text);
  
  if (users.length === 0) {
    alert('请输入有效的用户信息');
    return;
  }
  
  const existing = await chrome.storage.local.get(['users']);
  const allUsers = [...(existing.users || []), ...users];
  
  await chrome.storage.local.set({ users: allUsers });
  document.getElementById('userInput').value = '';
  loadUsers();
  showToast(`已保存 ${users.length} 个用户信息`);
});

// 加载用户列表
async function loadUsers() {
  const { users = [] } = await chrome.storage.local.get(['users']);
  const listEl = document.getElementById('userList');
  
  if (users.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无保存的用户信息</p>';
  } else {
    listEl.innerHTML = users.map(displayUser).join('');
    
    // 添加事件委托
    listEl.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', function() {
        const userId = this.getAttribute('data-user-id');
        const action = this.getAttribute('data-action');
        
        if (action === 'delete-user') {
          window.deleteUser(userId);
        } else if (action === 'edit-user') {
          window.editUser(userId);
        }
      });
    });
  }
}

window.deleteUser = async function(id) {
  const { users = [] } = await chrome.storage.local.get(['users']);
  const filtered = users.filter(u => u.id != id);
  await chrome.storage.local.set({ users: filtered });
  loadUsers();
  showToast('用户信息已删除');
};

window.editUser = function(id) {
  alert('编辑功能：请删除后重新添加');
};

// ============ 邮箱生成功能 ============

// 生成邮箱
document.getElementById('generateEmails').addEventListener('click', async () => {
  const prefix = document.getElementById('emailPrefix').value.trim();
  const suffix = document.getElementById('emailSuffix').value.trim();
  const count = parseInt(document.getElementById('emailCount').value);
  const mode = document.getElementById('emailMode').value;
  
  if (!prefix || !suffix) {
    alert('请输入邮箱前缀和后缀');
    return;
  }
  
  const emails = [];
  const existing = await chrome.storage.local.get(['emails']);
  const currentCount = (existing.emails || []).length;
  
  for (let i = 0; i < count; i++) {
    let email;
    if (mode === 'sequence') {
      email = `${prefix}${currentCount + i + 1}${suffix}`;
    } else {
      const random = Math.random().toString(36).substring(2, 8);
      email = `${prefix}${random}${suffix}`;
    }
    emails.push({
      email,
      id: Date.now() + Math.random() + i,
      type: 'generated'
    });
  }
  
  const allEmails = [...(existing.emails || []), ...emails];
  await chrome.storage.local.set({ emails: allEmails });
  loadEmails();
  showToast(`已生成 ${count} 个邮箱`);
});

// 添加固定邮箱
document.getElementById('addFixedEmails').addEventListener('click', async () => {
  const text = document.getElementById('fixedEmailInput').value;
  const lines = text.trim().split('\n').filter(line => line.trim() && line.includes('@'));
  
  if (lines.length === 0) {
    alert('请输入有效的邮箱地址');
    return;
  }
  
  const emails = lines.map(email => ({
    email: email.trim(),
    id: Date.now() + Math.random(),
    type: 'fixed'
  }));
  
  const existing = await chrome.storage.local.get(['emails']);
  const allEmails = [...(existing.emails || []), ...emails];
  
  await chrome.storage.local.set({ emails: allEmails });
  document.getElementById('fixedEmailInput').value = '';
  loadEmails();
  showToast(`已添加 ${lines.length} 个固定邮箱`);
});

// 显示邮箱
function displayEmail(email) {
  const icon = email.type === 'fixed' ? '📌' : '📧';
  return `
    <div class="item-card" data-id="${email.id}">
      <div class="item-content">
        <span class="email-icon">${icon}</span>
        <span class="email-text">${email.email}</span>
      </div>
      <div class="item-actions">
        <button class="btn btn-edit" data-email-id="${email.id}" data-action="edit-email">编辑</button>
        <button class="btn btn-delete" data-email-id="${email.id}" data-action="delete-email">删除</button>
      </div>
    </div>
  `;
}

// 加载邮箱列表
async function loadEmails() {
  const { emails = [] } = await chrome.storage.local.get(['emails']);
  const listEl = document.getElementById('emailList');
  const countEl = document.getElementById('emailCountDisplay');
  
  countEl.textContent = emails.length;
  
  if (emails.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无生成的邮箱</p>';
  } else {
    listEl.innerHTML = emails.map(displayEmail).join('');
    
    // 添加事件委托
    listEl.querySelectorAll('[data-action]').forEach(btn => {
      btn.addEventListener('click', function() {
        const emailId = this.getAttribute('data-email-id');
        const action = this.getAttribute('data-action');
        
        if (action === 'delete-email') {
          window.deleteEmail(emailId);
        } else if (action === 'edit-email') {
          window.editEmail(emailId);
        }
      });
    });
  }
}

window.deleteEmail = async function(id) {
  const { emails = [] } = await chrome.storage.local.get(['emails']);
  const filtered = emails.filter(e => e.id != id);
  await chrome.storage.local.set({ emails: filtered });
  loadEmails();
  showToast('邮箱已删除');
};

window.editEmail = function(id) {
  alert('编辑功能：请删除后重新添加');
};

// ============ 密码功能 ============

// 生成密码
document.getElementById('generatePassword').addEventListener('click', async () => {
  const length = parseInt(document.getElementById('passwordLength').value);
  const password = generateStrongPassword(length);
  
  const existing = await chrome.storage.local.get(['passwords']);
  const passwords = existing.passwords || [];
  passwords.push({
    password,
    id: Date.now(),
    createdAt: new Date().toLocaleString()
  });
  
  await chrome.storage.local.set({ passwords });
  loadPasswords();
  showToast('密码已生成');
});

function generateStrongPassword(length = 16) {
  const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*';
  let password = '';
  for (let i = 0; i < length; i++) {
    password += charset.charAt(Math.floor(Math.random() * charset.length));
  }
  return password;
}

// 加载密码列表
async function loadPasswords() {
  const { passwords = [] } = await chrome.storage.local.get(['passwords']);
  const listEl = document.getElementById('passwordList');
  
  if (passwords.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无保存的密码</p>';
  } else {
    listEl.innerHTML = passwords.map(p => `
      <div class="item-card" data-id="${p.id}">
        <div class="item-content">
          <span class="password-icon">🔐</span>
          <span class="password-text">${p.password}</span>
          <span class="password-time">${p.createdAt}</span>
        </div>
        <div class="item-actions">
          <button class="btn btn-edit" onclick="copyPassword('${p.password}')">复制</button>
          <button class="btn btn-delete" onclick="deletePassword('${p.id}')">删除</button>
        </div>
      </div>
    `).join('');
  }
}

window.copyPassword = function(password) {
  navigator.clipboard.writeText(password);
  showToast('密码已复制');
};

window.deletePassword = async function(id) {
  const { passwords = [] } = await chrome.storage.local.get(['passwords']);
  const filtered = passwords.filter(p => p.id != id);
  await chrome.storage.local.set({ passwords: filtered });
  loadPasswords();
  showToast('密码已删除');
};

// {{ AURA-X: Modify - 更新主程序功能逻辑. Approval: 寸止 }}
// ============ 主程序功能 ============

// 更新统计数据
async function updateMainStats() {
  const { cards = [], users = [], emails = [] } = await chrome.storage.local.get(['cards', 'users', 'emails']);
  
  document.getElementById('cardCount').textContent = cards.length;
  document.getElementById('userCount').textContent = users.length;
  document.getElementById('emailCountMain').textContent = emails.length;
  
  document.getElementById('cardStatusCount').textContent = `${cards.length} 张`;
  document.getElementById('userStatusCount').textContent = `${users.length} 个`;
  document.getElementById('emailStatusCount').textContent = `${emails.length} 个`;
}

// {{ AURA-X: Modify - 修复消息发送错误处理. Approval: 寸止 }}
// 仅注册
document.getElementById('btnRegisterOnly').addEventListener('click', async () => {
  const { cards, users, emails } = await chrome.storage.local.get(['cards', 'users', 'emails']);
  
  if (!users || users.length === 0) {
    alert('请先添加用户信息');
    return;
  }
  
  if (!emails || emails.length === 0) {
    alert('请先生成或添加邮箱');
    return;
  }
  
  console.log('[Popup] Sending registerOnly message');
  
  try {
    const response = await chrome.runtime.sendMessage({
      action: 'registerOnly',
      data: { user: users[0], email: emails[0] }
    });
    console.log('[Popup] Response:', response);
    showToast('开始注册流程...');
  } catch (error) {
    console.error('[Popup] Error:', error);
    showToast('错误：' + error.message);
  }
});

// 仅绑卡
document.getElementById('btnBindOnly').addEventListener('click', async () => {
  const { cards, plan } = await chrome.storage.local.get(['cards', 'plan']);
  
  if (!cards || cards.length === 0) {
    alert('请先添加卡信息');
    return;
  }
  
  try {
    await chrome.runtime.sendMessage({
      action: 'bindCardOnly',
      data: { card: cards[0], plan: plan || 'pro-basic' }
    });
    showToast('开始绑卡流程...');
  } catch (error) {
    console.error('[Popup] Error:', error);
    showToast('错误：' + error.message);
  }
});

// 注册+绑卡
document.getElementById('btnRegisterAndBind').addEventListener('click', async () => {
  const { cards, users, emails, plan } = await chrome.storage.local.get(['cards', 'users', 'emails', 'plan']);
  
  if (!cards || cards.length === 0) {
    alert('请先添加卡信息');
    return;
  }
  
  if (!users || users.length === 0) {
    alert('请先添加用户信息');
    return;
  }
  
  if (!emails || emails.length === 0) {
    alert('请先生成或添加邮箱');
    return;
  }
  
  try {
    await chrome.runtime.sendMessage({
      action: 'registerAndBind',
      data: {
        card: cards[0],
        user: users[0],
        email: emails[0],
        plan: plan || 'pro-basic'
      }
    });
    showToast('开始完整流程...');
  } catch (error) {
    console.error('[Popup] Error:', error);
    showToast('错误：' + error.message);
  }
});

// 套餐选择
document.getElementById('planSelect').addEventListener('change', (e) => {
  chrome.storage.local.set({ plan: e.target.value });
  showToast('套餐已保存');
});

// 操作手册
document.getElementById('showManual').addEventListener('click', () => {
  window.open('https://aigcview.top/', '_blank');
});

// ============ 工具函数 ============

function showToast(message) {
  const toast = document.createElement('div');
  toast.className = 'toast';
  toast.textContent = message;
  document.body.appendChild(toast);
  
  setTimeout(() => {
    toast.classList.add('show');
  }, 100);
  
  setTimeout(() => {
    toast.classList.remove('show');
    setTimeout(() => toast.remove(), 300);
  }, 2000);
}

// ============ 已注册账号 ============

async function loadRegisteredAccounts() {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const listEl = document.getElementById('registeredAccountsList');
  
  if (!listEl) return;
  
  if (registeredAccounts.length === 0) {
    listEl.innerHTML = '<p class="empty-hint">暂无已注册账号</p>';
  } else {
    listEl.innerHTML = `
      <div style="margin-bottom: 10px; display: flex; gap: 8px;">
        <button class="btn btn-primary" onclick="exportAllAccounts()" style="flex: 1;">📤 导出全部</button>
        <button class="btn btn-primary" onclick="copyAllTokens()" style="flex: 1;">📋 复制Token</button>
        <button class="btn btn-danger" onclick="clearAllAccounts()" style="flex: 1;">🗑️ 清空</button>
      </div>
      ${registeredAccounts.map((acc, idx) => {
        // 邮箱部分隐藏显示
        const email = acc.email || 'Unknown';
        const emailParts = email.split('@');
        let maskedEmail = email;
        if (emailParts.length === 2) {
          const localPart = emailParts[0];
          const domain = emailParts[1];
          if (localPart.length > 6) {
            maskedEmail = localPart.substring(0, 3) + '****' + localPart.substring(localPart.length - 2) + '@' + domain;
          } else if (localPart.length > 2) {
            maskedEmail = localPart.substring(0, 2) + '****' + '@' + domain;
          }
        }
        
        // 格式化过期时间
        let expiryDisplay = '未知';
        if (acc.nextBillingDate) {
          try {
            const date = new Date(acc.nextBillingDate);
            expiryDisplay = (date.getMonth() + 1) + '/' + date.getDate() + ' ' + 
                           String(date.getHours()).padStart(2, '0') + ':' + 
                           String(date.getMinutes()).padStart(2, '0');
          } catch (e) {
            expiryDisplay = acc.nextBillingDate;
          }
        }
        
        // {{ AURA-X: Modify - 修复tenant显示. Approval: 寸止 }}
        // 提取tenant域名显示
        let tenantDisplay = acc.tenant_url || 'Unknown';
        if (tenantDisplay !== 'Unknown' && tenantDisplay.includes('://')) {
          tenantDisplay = tenantDisplay.replace('https://', '').replace('http://', '').replace('/', '');
        }
        
        return `
        <div class="account-card" data-id="${acc.id}">
          <div class="account-header">
            <div class="account-tenant">${tenantDisplay}</div>
            <div class="account-status">✅ 正常</div>
          </div>
          <div class="account-date-row">${acc.registeredAt || '未知'}</div>
          <div class="account-email-row">
            <span class="email-icon">📧</span>
            <span class="email-text">${maskedEmail}</span>
            <button class="copy-icon-btn" onclick="copyToClipboard('${email}')" title="复制完整邮箱">📋</button>
          </div>
          <div class="account-info">
            <div class="info-badge info-expiry">
              <span class="badge-label">过期：</span>
              <span class="badge-value">${expiryDisplay}</span>
            </div>
            <div class="info-badge info-credits">
              <span class="badge-label">剩余：</span>
              <span class="badge-value">${acc.credits || 0}</span>
            </div>
          </div>
          <div class="account-actions">
            <button class="action-icon-btn" onclick="copyAccountSession('${acc.id}')" title="复制Session">🔑</button>
            <button class="action-icon-btn" onclick="copyAccountToken('${acc.id}')" title="复制Token">📋</button>
            <button class="action-icon-btn" onclick="copyAccountInfo('${acc.id}')" title="复制全部信息">📄</button>
            <button class="action-icon-btn" onclick="openPortalUrl('${acc.id}')" title="打开Portal">🔗</button>
            <button class="action-icon-btn" onclick="refreshAccountInfo('${acc.id}')" title="刷新信息">🔄</button>
            <button class="action-icon-btn" onclick="editAccount('${acc.id}')" title="编辑">✏️</button>
            <button class="action-icon-btn delete-btn" onclick="deleteAccount('${acc.id}')" title="删除">🗑️</button>
          </div>
        </div>
      `;
      }).join('')}
    `;
  }
}

// {{ AURA-X: Add - 复制Session功能. Approval: 寸止 }}
window.copyAccountSession = async function(id) {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const account = registeredAccounts.find(a => a.id == id);
  
  if (account && account.session) {
    navigator.clipboard.writeText(account.session);
    showToast('Session已复制');
  } else if (account && account.token) {
    // 如果没有session，尝试复制token
    navigator.clipboard.writeText(account.token);
    showToast('Token已复制（无Session）');
  } else {
    showToast('该账号未获取到Session/Token');
  }
};

window.copyAccountToken = async function(id) {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const account = registeredAccounts.find(a => a.id == id);
  
  if (account && account.token) {
    navigator.clipboard.writeText(account.token);
    showToast('Token已复制');
  } else if (account && account.session) {
    // 如果没有token，尝试复制session
    navigator.clipboard.writeText(account.session);
    showToast('Session已复制（无Token）');
  } else {
    showToast('该账号未获取到Token/Session');
  }
};

// {{ AURA-X: Modify - 包含session在复制信息中. Approval: 寸止 }}
window.copyAccountInfo = async function(id) {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const account = registeredAccounts.find(a => a.id == id);
  
  if (account) {
    const text = JSON.stringify({
      email: account.email,
      session: account.session,
      token: account.token,
      code: account.code,
      state: account.state,
      tenant_url: account.tenant_url,
      credits: account.credits,
      planName: account.planName,
      nextBillingDate: account.nextBillingDate,
      portalUrl: account.portalUrl
    }, null, 2);
    
    navigator.clipboard.writeText(text);
    showToast('账号信息已复制');
  }
};

// {{ AURA-X: Add - 辅助功能. Approval: 寸止 }}
window.copyToClipboard = function(text) {
  navigator.clipboard.writeText(text);
  showToast('已复制');
};

window.refreshAccountInfo = async function(id) {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const account = registeredAccounts.find(a => a.id == id);
  
  if (!account || !account.session) {
    showToast('无法刷新：缺少Session');
    return;
  }
  
  showToast('正在刷新账号信息...');
  
  try {
    // 调用API获取最新信息
    const subscriptionRes = await fetch('https://app.augmentcode.com/api/subscription', {
      headers: {
        'Cookie': `_session=${account.session}`
      }
    });
    
    if (subscriptionRes.ok) {
      const subscriptionData = await subscriptionRes.json();
      account.planName = subscriptionData.plan?.name || subscriptionData.planName;
      account.nextBillingDate = subscriptionData.nextBillingDate || subscriptionData.next_billing_date;
      account.portalUrl = subscriptionData.portalUrl || subscriptionData.portal_url;
    }
    
    const creditsRes = await fetch('https://app.augmentcode.com/api/credits', {
      headers: {
        'Cookie': `_session=${account.session}`
      }
    });
    
    if (creditsRes.ok) {
      const creditsData = await creditsRes.json();
      account.credits = creditsData.remaining || creditsData.credits || 0;
      account.totalCredits = creditsData.total || 30000;
      account.usedCredits = creditsData.used || 0;
    }
    
    account.updatedAt = new Date().toLocaleString();
    await chrome.storage.local.set({ registeredAccounts });
    loadRegisteredAccounts();
    showToast('账号信息已刷新');
  } catch (error) {
    console.error('[Popup] Failed to refresh account:', error);
    showToast('刷新失败');
  }
};

window.editAccount = async function(id) {
  showToast('编辑功能开发中...');
};

window.deleteAccount = async function(id) {
  if (!confirm('确定删除此账号？')) return;
  
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const filtered = registeredAccounts.filter(a => a.id != id);
  await chrome.storage.local.set({ registeredAccounts: filtered });
  loadRegisteredAccounts();
  updateMainStats();
  showToast('账号已删除');
};

window.exportAllAccounts = async function() {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  
  if (registeredAccounts.length === 0) {
    showToast('暂无账号可导出');
    return;
  }
  
  const exportData = registeredAccounts.map(acc => ({
    email: acc.email,
    code: acc.code,
    state: acc.state,
    tenant_url: acc.tenant_url,
    token: acc.token,
    registeredAt: acc.registeredAt
  }));
  
  const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `augment-accounts-${Date.now()}.json`;
  a.click();
  URL.revokeObjectURL(url);
  
  showToast(`已导出${registeredAccounts.length}个账号`);
};

window.copyAllTokens = async function() {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  
  const tokens = registeredAccounts
    .filter(acc => acc.token)
    .map((acc, idx) => `${idx + 1}. ${acc.email}\n   Token: ${acc.token}`)
    .join('\n\n');
  
  if (!tokens) {
    showToast('暂无可用Token');
    return;
  }
  
  navigator.clipboard.writeText(tokens);
  showToast('所有Token已复制');
};

window.clearAllAccounts = async function() {
  if (!confirm('确定清空所有已注册账号？此操作不可恢复！')) return;
  
  await chrome.storage.local.set({ registeredAccounts: [] });
  loadRegisteredAccounts();
  updateMainStats();
  showToast('已清空所有账号');
};

window.openPortalUrl = async function(id) {
  const { registeredAccounts = [] } = await chrome.storage.local.get(['registeredAccounts']);
  const account = registeredAccounts.find(a => a.id == id);
  
  if (account && account.portalUrl) {
    window.open(account.portalUrl, '_blank');
  } else {
    showToast('该账号无Portal URL');
  }
};

// ============ 初始化 ============

document.addEventListener('DOMContentLoaded', () => {
  loadCards();
  loadUsers();
  loadEmails();
  loadPasswords();
  loadRegisteredAccounts();
  updateMainStats();
  
  // 加载删除设置
  chrome.storage.local.get(['deleteAfterSuccess'], (data) => {
    document.getElementById('deleteAfterSuccess').checked = data.deleteAfterSuccess || false;
  });
  
  // 保存删除设置
  document.getElementById('deleteAfterSuccess').addEventListener('change', (e) => {
    chrome.storage.local.set({ deleteAfterSuccess: e.target.checked });
  });
  
  // 加载套餐选择
  chrome.storage.local.get(['plan'], (data) => {
    if (data.plan) {
      document.getElementById('planSelect').value = data.plan;
    }
  });
  
  // 监听数据变化，更新统计
  chrome.storage.onChanged.addListener((changes, area) => {
    if (area === 'local') {
      updateMainStats();
      loadCards();
      loadUsers();
      loadEmails();
    }
  });
});
